<?php

namespace App\Http\Controllers\Admin;

use Validator;
use App\Member;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class MemberController extends Controller
{
    public function index(Request $request)
    {
        $members = Member::get();
        return view('admin.member.index', [
            'request' => $request,
            'members' => $members
        ]);
    }

    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->except(['_token']);
            $rules = [
                'name' => 'required|min:2|max:10',
                'pwd' => 'required|min:6|max:20'
            ];
            $messages = [
                'name.required' => '请输入管理员名！',
                'name.min' => '管理名至少2个字符！',
                'name.max' => '管理名最多10个字符！',
                'pwd.required' => '请输入管理员密码！',
                'pwd.min' => '密码至少6个字符',
                'pwd.max' => '密码最多20字符'
            ];
            $validator = Validator::make($data, $rules, $messages);
            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator)->withInput();
            }
            $member = new Member();
            $member->name = $data['name'];
            $member->pwd = encrypt($data['pwd']);
            $member->save();
            return redirect('admin/member');
        }
        return view('admin.member.add', [
            'request' => $request
        ]);
    }

    public function edit(Request $request, $id)
    {
        if ($request->isMethod('post')) {
            $data = $request->except(['_token']);
            $rules = [
                'name' => 'required|min:2|max:10'
            ];
            $messages = [
                'name.required' => '请输入管理员名！',
                'name.min' => '管理名至少2个字符！',
                'name.max' => '管理名最多10个字符！'
            ];
            $validator = Validator::make($data, $rules, $messages);
            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator)->withInput();
            }
            $member = Member::find($data['id']);
            $member->name = $data['name'];
            if (!empty($data['pwd'])) {
                $member->pwd = encrypt($data['pwd']);
            }
            $member->save();
            return redirect('admin/member');
        }
        $member = Member::find($id);
        if (!isset($member->name)) {
            return redirect('admin/member');
        }
        return view('admin.member.edit', [
            'request' => $request,
            'member' => $member
        ]);
    }

    public function del(Request $request)
    {
        $id = $request->input('id');
        $member = Member::find($id);
        if ($member->delete()) {
            $return = ['code' => 0];
        } else {
            $return = ['code' => __LINE__, 'msg' => '删除失败'];
        }
        return response()->json($return);
    }
}